const Router = require('koa-router')
const router = new Router({
    prefix: "/api/admin/admin"
})

const Admin = require('../../models/admin')
const {
    createToken,
    parseToken
} = require('../../utils/token')
const {
    Success,
    Error
} = require('../../utils/response')

router.post('/login', async (ctx) => {
    const {
        username,
        password
    } = ctx.request.body
    if (!username || !password) {
        ctx.body = Error('未携带指定参数')
    } else {
        let data = await Admin.findAll({
            where: {
                username,
                password
            }
        })
        if (data.length > 0) {
            let token = createToken(data[0])
            ctx.body = Success(token)
        } else {
            ctx.body = Error('用户名或密码错误')
        }
    }
})

router.get('/info', async (ctx) => {
    ctx.body = Success(await parseToken(ctx.header['authorization']))
})

module.exports = router